/**
 * Created by Administrator on 2017/3/10.
 */

var common = module.exports;
var crypto = require('crypto');
var request = require('request');
var CONFIG = require('../config/config_local');
var goodsDao = require('../dao/goods');
common.randomString = function(len) {
    len = len || 32;
    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var maxPos = $chars.length;
    var pwd = '';
    for (var i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
};

//格林威治时间转换
common.handle = function (data) {
    if(data.created_date != undefined) {
        data.created_date = format_time(data.created_date);
    }

    if(data.updated_date != undefined) {
        data.updated_date = format_time(data.updated_date);
    }
    return data;
}

common.getAppSign  = function (APP_key,APP_secret,t){
    var md5=crypto.createHash('md5');
    md5.update(APP_key+APP_secret+t);
    var sign = md5.digest('hex');
    return sign;
}

function format_time(str) {
   if(str.indexOf('.000Z') >= 0) {
       str = str.replace(/T/,' ');
       str = str.replace(/.000Z/,' ');
       var a1;
       var a2;
       a1 = str.split(' ');
       a2 = a1[1].split(':');
       a2[0] =parseInt(a2[0]) + 8;
       if(a2[0] >= 24) {
           a1[0] = a1[0].split('-');
           a1[0][2] = parseInt(a1[0][2]) + 1;
           a1[0] = a1[0].join('-');
           a2[0] = a2[0]-24;
           if(a2[0] < 10) {
               a2[0] = '0'+a2[0];
           }
       }
       a2 = a2.join(':');
       var update_time = a1[0]+' '+a2;
       return update_time;
   } else {
       return  str;
   }
}

common.formatDate = function(now, onlyDate) {
    var year=now.getFullYear();
    var month=now.getMonth()+1;
    var date=now.getDate();
    var hour = now.getHours();
    var minute = now.getMinutes();
    var second = now.getSeconds();

    if(month<10){
        month = '0'+month;
    }
    if(date<10){
        date = '0'+date;
    }
    if(hour<10){
        hour = '0'+hour;
    }
    if(minute<10){
        minute = '0'+minute;
    }
    if(second<10){
        second = '0'+second;
    }
    if(onlyDate) {
        return year+"-"+month+"-"+date+" 00:00:00";
    } else {
        return year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second;
    }
}

common.convertToUnicode = function(data) {
    var reg = /\\u[0-9a-f]{4}/igm;
    return data.replace(reg, function () {
        return String.fromCharCode(parseInt(arguments[0].substr(2, 4),16).toString())
    });
}

common.GetQueryString = function GetQueryString(url, name){
    var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
    var r = url.match(reg);
    if(r!=null)return  unescape(r[2]); return null;
}

common.postToUserCenter = function(options, cb) {
    request(options, function(error, response, body){
        if(!body) {
            cb('登录发生错误！');
        } else {
            body = JSON.parse(body);
            if(body.status == 200) {
                cb(null, body.payload);
            } else {
                cb(body.err);
            }
        }
    });
}

common.baseRequest = function(host, path, param, callback) {
    var url = host + path;
    var form = '';
    for(var key in param){
        if(param[key]) {
            form += key + '='  + param[key] + '&';
        }
    }
    var options = {
        url: url,
        method: 'POST',
        form: form
    };
    request(options, function (error, response, body) {
        if (error || !response || !response.statusCode ||response.statusCode != 200 || !body) {
            callback('服务器异常，请稍后重试');
            return;
        } else {
            callback(body);
            // body = JSON.parse(body);
            // if(body.status == 200) {
            //     callback(null, body.payload);
            // } else {
            //     callback(body.err);
            // }
        }
    });
}

common.duplicateRemoval = function(dbData, data, PDAdd) {
    if(dbData.length > 0) {
        var arr = [];
        for(var i=0; i<dbData.length; i++) {
            if(dbData[i].source == 'HTK') {
                arr.push(dbData[i]);
            }
        }


        if(!PDAdd) {
            for(var i=0; i<data.length; i++) {
                for(var j=0; j<dbData.length; j++) {
                    if(data[i] != undefined && dbData[j] != undefined && data[i].auctionId == dbData[j].auctionId && data[i].hiddenAmount < dbData[j].hiddenAmount) {
                        delete data[i];
                    }
                    if(data[i] != undefined && dbData[j] != undefined && data[i].auctionId == dbData[j].auctionId && data[i].hiddenAmount == dbData[j].hiddenAmount
                        && data[i].hiddenActivityId == dbData[j].hiddenActivityId && data[i].realTkRate == dbData[j].realTkRate) {
                        delete data[i];
                    }
                }
            }
        }

        if(arr.length > 0) {
            var htkArr = [];
            for(var i=0; i<data.length; i++) {
                for(var j=0; j<arr.length; j++) {
                    if(data[i] != undefined && arr[j] != undefined && data[i].auctionId == arr[j].auctionId && parseInt(data[i].hiddenAmount) > parseInt(arr[j].hiddenAmount)) {
                        htkArr.push(arr[j].pdId);
                    }
                    if(data[i] != undefined && arr[j] != undefined && data[i].auctionId == arr[j].auctionId && parseInt(data[i].hiddenAmount) <= parseInt(arr[j].hiddenAmount)) {
                        if(data[i].hiddenAmount == arr[j].hiddenAmount ) {
                            goodsDao.updateExtActivityId(data[i].auctionId, data[i].hiddenActivityId);
                        }
                        delete data[i];
                    }
                }
            }

            if(htkArr.length > 0 ) {
                //  通知pds
                var param = {};
                param.app_time = new Date().getTime();
                param.app_key = 'blpd';
                param.status_reason = '不是最优券！';
                param.ids = JSON.stringify(htkArr);
                param.app_sign = common.getAppSign (param.app_key, CONFIG.APP_secret, param.app_time);
                // 'serverGood/offGoodsByBenliu'
                common.baseRequest(CONFIG.PaoDanHost, 'serverGood/offGoodsByBenliu', param, function(err, data){
                    if(err) {
                        console.log(err);
                    } else {
                        console.log(data);
                    }
                })
            }

            var goods = [];
            for(var i=0; i<data.length; i++) {
                if(data[i] != undefined) {
                    goods.push(data[i]);
                }
            }
            return goods;
        } else {
            var goods = [];
            for(var i=0; i<data.length; i++) {
                if(data[i] != undefined) {
                    goods.push(data[i]);
                }
            }
            return goods;
        }
    } else {
        return data;
    }
}

Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};
